package com.mdc.mansion.common.util.log;
import com.mdc.mansion.common.util.BeanUtils;
import com.mdc.mansion.common.util.DateUtils;
import org.slf4j.Logger;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LoggerUtil{

	/** 字段分隔符 */
	protected static final String separator = BeanUtils.SEPARATOR;

	/**
	 * 记录info信息
	 * @param access 执行的时间
	 * @param time 执行的时间长度
	 * @param descrip 描述
	 * @param seq 一次完整的请求的序列号
	 * @param req 方法的请求参数
	 * @param rsp 方法的返回参数
	 */
	public static void loggerInfo(Logger logger,Date access, long time,String descrip,String seq, Object rsp,Object ...req) {
		log(logger,access, time, descrip, seq, null, rsp, req);
	}
	
	/**
	 * 记录error错误
	 * @param access
	 * @param time
	 * @param descrip
	 * @param seq
	 * @param t
	 * @param rsp
	 * @param req
	 */
	public static void loggerError(Logger logger,Date access, long time,String descrip,String seq,Throwable t,Object rsp, Object ...req) {
		log(logger,access, time, descrip, seq, t, rsp, req);
	}

	/**
	 * 记录debug信息
	 * 主要是在开发，测试，准线阶段使用
	 * @param logger
	 * @param access
	 * @param descrip
	 * @param seq
	 */
	public static void loggerDebug(Logger logger,Date access, String descrip,String seq) {
		StringBuilder builder = new StringBuilder();
		builder.append("access={}").append(separator).append("descrip={}").append(separator).append("seq={}");
		logger.debug(builder.toString(),DateUtils.formatFullStandardDateTime(access),descrip,seq);
	}
	
	private static void log(Logger logger,Date access, long time,String descrip,String seq, Throwable t, Object rsp,Object ...req) {
		List<Object> list = new ArrayList<Object>();
		if (access != null) {
			list.add(DateUtils.formatFullStandardDateTime(access));
		}
		list.add(time);
		list.add(descrip);
		list.add(seq);
		StringBuilder builder = new StringBuilder();
		builder.append("access={}");
		builder.append(separator).append("time={}");
		builder.append(separator).append("descrip={}");
		builder.append(separator).append("seq={}");
		if(req!=null&&req.length>0){
			builder.append(separator).append("req={}");
			String reqs="";
			for(Object rq:req){
				reqs+=BeanUtils.getBeanInfo(rq)+"###";
			}
			list.add(reqs);
		}
		if(rsp!=null){
			builder.append(separator).append("rsp={}");
			list.add(BeanUtils.getBeanInfo(rsp));
		}
		if (t != null) {
			builder.append(separator).append("{}");
			list.add(t);
			logger.error(builder.toString(), list.toArray());
		} else {
			logger.info(builder.toString(), list.toArray());
		}
	}
}
